package me.flyray.biz.thymeleaf.modules.pay.biz;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.wxiaoqi.security.common.enums.CustomerTypeEnums;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import me.flyray.biz.thymeleaf.modules.goods.entity.QrGoodsInfo;
import me.flyray.biz.thymeleaf.modules.goods.entity.QrGoodsMonthStatistics;
import me.flyray.biz.thymeleaf.modules.goods.entity.QrGoodsOrder;
import me.flyray.biz.thymeleaf.modules.goods.mapper.QrGoodsInfoMapper;
import me.flyray.biz.thymeleaf.modules.goods.mapper.QrGoodsMonthStatisticsMapper;
import me.flyray.biz.thymeleaf.modules.goods.mapper.QrGoodsOrderMapper;
import me.flyray.biz.thymeleaf.modules.pay.entity.CmsPayOrder;
import me.flyray.biz.thymeleaf.modules.pay.mapper.CmsPayOrderMapper;

/**
 * 支付回调处理
 * @author he
 *
 */
@Service
public class PayCallBackBiz {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(PayCallBackBiz.class);

	@Autowired
	private CmsPayOrderMapper cmsPayOrderMapper;
	@Autowired
	private QrGoodsOrderMapper qrGoodsOrderMapper;
	@Autowired
	private QrGoodsInfoMapper qrGoodsInfoMapper;
	@Autowired
	private QrGoodsMonthStatisticsMapper qrGoodsMonthStatisticsMapper;

	/**
	 * 支付完成回调
	 * @param request
	 * @return
	 */
	public void payCallBack(Map<String, Object> params){
		logger.info("支付完成回调开始.......{}",params);
		String platformId = (String) params.get("platformId");
		String orderNo = (String) params.get("orderNo");
		String txStatus = (String) params.get("txStatus");
		String amount = (String) params.get("amount");
		BigDecimal amountDecimal = new BigDecimal(amount);
		CmsPayOrder cmsScenesOrder = new CmsPayOrder();
		cmsScenesOrder.setPlatformId(platformId);
		cmsScenesOrder.setPayOrderNo(orderNo);
		CmsPayOrder selectCmsPayOrder = cmsPayOrderMapper.selectOne(cmsScenesOrder);
		if(null == selectCmsPayOrder){
			logger.info("支付完成回调-订单不存在.......");
			return;
		}
		if(0 != selectCmsPayOrder.getTxAmt().compareTo(amountDecimal)){
			logger.info("支付完成回调-金额不一致.......");
			return;
		}

		//支付成功入账，更新订单状态
		if("00".equals(txStatus)){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("platformId", (String) params.get("platformId"));
			map.put("orderNo", (String) params.get("orderNo"));
			map.put("intoAccAmt", (String) params.get("amount"));
			map.put("merchantId", selectCmsPayOrder.getMerchantId());
			map.put("merchantType", "CUST01");
			if("1".equals(selectCmsPayOrder.getPayCode())){//支付
				map.put("accountType", "ACC001");
				map.put("customerType", CustomerTypeEnums.mer_user.getCode());
				map.put("tradeType", "01");//支付
			}else if("2".equals(selectCmsPayOrder.getPayCode())){//充值
				map.put("personalId", selectCmsPayOrder.getPersonalId());
				map.put("accountType", "ACC011");
				map.put("customerType", CustomerTypeEnums.per_user.getCode());
				map.put("tradeType", "04");//充值
			}
			selectCmsPayOrder.setTxStatus("00");//支付成功
		}else{
			selectCmsPayOrder.setTxStatus("01");//支付失败
		}
		cmsPayOrderMapper.updateByPrimaryKey(selectCmsPayOrder);
		
		//更新场景订单
		this.updateScenesOrder(params);

		logger.info("支付完成回调结束.......");
	}
	
	/**
	 * 更新场景订单
	 * @param params
	 */
	private void updateScenesOrder(Map<String, Object> params){
		QrGoodsOrder qrGoodsOrder = new QrGoodsOrder();
		qrGoodsOrder.setPlatformId((String) params.get("platformId"));
		qrGoodsOrder.setPayOrderNo((String) params.get("orderNo"));
		QrGoodsOrder selectQrGoodsOrder = qrGoodsOrderMapper.selectOne(qrGoodsOrder);
		if(null != selectQrGoodsOrder){
			if("00".equals((String) params.get("txStatus"))){
				selectQrGoodsOrder.setStatus("00");//支付成功
			}else{
				selectQrGoodsOrder.setStatus("01");//支付失败
			}
			qrGoodsOrderMapper.updateByPrimaryKey(selectQrGoodsOrder);
			//新增商品付费次数
			QrGoodsInfo qrGoodsInfo = new QrGoodsInfo();
			qrGoodsInfo.setPlatformId(selectQrGoodsOrder.getPlatformId());
			qrGoodsInfo.setMerchantId(selectQrGoodsOrder.getMerchantId());
			qrGoodsInfo.setGoodsId(selectQrGoodsOrder.getGoodsId());
			QrGoodsInfo selectQrGoodsInfo = qrGoodsInfoMapper.selectOne(qrGoodsInfo);
			if(null != selectQrGoodsInfo){
				Long payCount = selectQrGoodsInfo.getPayCount();
				if(payCount == 0){
					selectQrGoodsInfo.setFirstPayDate(new Date());
				}
				selectQrGoodsInfo.setPayCount(payCount + 1);
				qrGoodsInfoMapper.updateByPrimaryKey(selectQrGoodsInfo);
			}
			//记录月份付费次数统计
			Date date = new Date();
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
	        QrGoodsMonthStatistics qrGoodsMonthStatistics = new QrGoodsMonthStatistics();
	        qrGoodsMonthStatistics.setGoodsId(selectQrGoodsOrder.getGoodsId());
	        qrGoodsMonthStatistics.setMonth(sdf.format(date));
			QrGoodsMonthStatistics selectGoodsMonthStatistics = qrGoodsMonthStatisticsMapper.selectOne(qrGoodsMonthStatistics);
			if(null == selectGoodsMonthStatistics){
				//新增一条当月记录
				qrGoodsMonthStatistics.setQuantity(1);
				qrGoodsMonthStatisticsMapper.insert(qrGoodsMonthStatistics);
			}else{
				//支付次数加1
				Integer quantity = selectGoodsMonthStatistics.getQuantity();
				selectGoodsMonthStatistics.setQuantity(quantity + 1);
				qrGoodsMonthStatisticsMapper.updateByPrimaryKey(selectGoodsMonthStatistics);
			}
		}
	}
	
}
